// pages/valveInformation/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //设备信息
    deviceInfo: {},
    // 阀门信息
    valveInformation: {
      //阀门开度
      valveOpening: 20,
      //供水温度
      supplyWaterTemperature: 20,
      //回水温度
      returnWaterTemperature: 20,
      //电池电压
      batteryVoltage: 20
    },

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    //获取设备id
    this.setData({
      deviceId: options.deviceId
    })
    //获取设备信息
    this.getDeviceInfoById(options.deviceId)
    // 改变标题
    wx.setNavigationBarTitle({
      title: this.data.deviceInfo.name
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getServiceId()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  //按照设备id获取设备信息
  getDeviceInfoById(deviceId) {
    console.log(deviceId)
    wx.getBluetoothDevices({
      success: (res) => {
        console.log(res)
        res.devices.forEach((item, index) => {
          if (item.deviceId == deviceId) {
            console.log(item)
            this.setData({
              deviceInfo: item
            })
          }
        })
        // wx.hideLoading()
      },
      fail: (res) => {
        console.log(res)
      }
    })
  },
  valveOpeningChangeHandle(e) {
    console.log(e)
    if (e.type == 'blur') {
      this.valveOpeningChange(e.detail.value)
    } else if (e.type == 'plus') {
      this.valveOpeningChange(this.data.valveInformation.valveOpening + 1)
    } else if (e.type == 'minus') {
      this.valveOpeningChange(this.data.valveInformation.valveOpening - 1)
    }
  },
  valveOpeningChange(valveOpening) {
    if (valveOpening < 0) {
      valveOpening = 0
    }
    if (valveOpening > 100) {
      valveOpening = 100
    }
    wx.showLoading({
      title: '发送指令中...',
      mask: true
    });
    setTimeout(() => {
      wx.hideLoading();
    }, 500);
    this.setData({
      valveInformation: {
        ...this.data.valveInformation,
        valveOpening: valveOpening
      }
    });
  },
  // 获取服务id
  getServiceId() {
    var that = this
    wx.getBLEDeviceServices({
      deviceId: that.data.deviceInfo.deviceId,
      success: function (res) {
        console.log(res)
        var model = res.services[0]
        that.setData({
          serviceId: model.uuid
        })
        that.getCharacteId()
      },
      fail: function (res) {
        console.log(res)
        wx.showToast({
          title: res.errMsg,
          icon: 'none',
          duration: 1500,
          mask: false,
          success: (result) => {

          },
          fail: () => { },
          complete: () => { }
        });
      }
    })
  },
  // 获取特征值
  getCharacteId() {
    var that = this
    wx.getBLEDeviceCharacteristics({
      deviceId: that.data.deviceInfo.deviceId,
      serviceId: that.data.serviceId,
      success: function (res) {
        for (var i = 0; i < res.characteristics.length; i++) {
          var model = res.characteristics[i]
          if (model.properties.notify == true) {
            that.setData({
              notifyId: model.uuid
            })

            //重点：开启监听服务。监听设备数据变化
            that.startNotice(model.uuid)
          }
          if (model.properties.write == true) {
            that.setData({
              writeId: model.uuid
            })
          }
        }

        //有可写权限
        // if (that.data.writeId != '') {
        //   wx.hideLoading()
        //   wx.showLoading({
        //     title: '通讯中...',
        //   })
        //   //这里可以完成需要下发到设备上的指令的生成
        //   that.sendCmd(value)
        // } else {
        //   wx.showToast({
        //     title: '失败: 设备无写入权限!',
        //     icon: 'none',
        //     duration: 2000
        //   })
        // }
      }
    })
  },
  startNotice(uuid) {
    var that = this
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      deviceId: that.data.deviceInfo.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: uuid,
      success: function (res) {
        var deviceResult = ''
        //特征数据变化
        wx.onBLECharacteristicValueChange(function (res) {
          deviceResult = deviceResult + util.arrayBufferToString(res.value) //应答数据比较长，会触发多次
          //如果应答帧总长度大于数据包长度，并且包含“16”，则说明是完整的应答帧
          if (deviceResult.lastIndexOf('16') >= (deviceResult.length - 8) && deviceResult.indexOf('68') >= 0) {
            //解析应答帧  这里开始对设备应答数据进行处理了

            deviceResult = ''
          }
        })
      }
    })
  },
  writeCharacterToDevice(buffer) {
    var that = this

    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceInfo.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.writeId,
      value: buffer,
      fail: function () {
        wx.showToast({
          title: '写入设备数据失败！',
          icon: 'none',
          duration: 2000
        })

      },
      success: function () {
        wx.showToast({
          title: '指令发送成功',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  //发送指令
  sendCmd(cmdValue) {
    var that = this

    if (cmdValue != '' && cmdValue != null && cmdValue != undefined) {
      that.writeCharacterToDevice(util.stringToArrayBuffer(cmdValue))
    } else {
      wx.showToast({
        title: '获取设备指令失败',
        icon: 'none',
        duration: 2000
      })
    }
  },
  //获取阀门开度
  getValveOpen() {
    var that = this
    var value = 'FEFEFEFE680400000000006816'
    that.sendCmd(value)
  },
  //获取供水温度
  getWaterTemperature() {
    var that = this
    var value = 'FEFEFEFE680400000000006816'
    that.sendCmd(value)
  },
  //获取回水温度
  getBackWaterTemperature() {
    var that = this
    var value = 'FEFEFEFE680400000000006816'
    that.sendCmd(value)
  },
  //获取阀门状态
  getValveStatus() {
    var that = this
    var value = 'FEFEFEFE680400000000006816'
    that.sendCmd(value)
  },
  //获取阀门电压
  getValveVoltage() {
    var that = this
    var value = 'FEFEFEFE680400000000006816'
    that.sendCmd(value)
  },
  //获取阀门电流
  getValveCurrent() {
    var that = this
    var value = 'FEFEFEFE680400000000006816'
    that.sendCmd(value)
  },
  //控制阀门开度
  controlValveOpen() {
    var that = this
    var value = 'FEFEFEFE680400000000006816'
    that.sendCmd(value)
  }
})